package com.skwen.delivery.superdelivery;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.databinding.DataBindingUtil;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.design.widget.NavigationView;
import android.support.design.widget.Snackbar;
import android.support.v4.view.GravityCompat;
import android.support.v7.app.ActionBarDrawerToggle;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.skwen.delivery.superdelivery.address.ReceiveAddress;
import com.skwen.delivery.superdelivery.address.SendAddress;
import com.skwen.delivery.superdelivery.cityselect.CityActivity;
import com.skwen.delivery.superdelivery.cityselect.entity.City;
import com.skwen.delivery.superdelivery.databinding.ActivityMainBinding;
import com.skwen.delivery.superdelivery.deliveryOrder.SendDeliveryOrder;
import com.skwen.delivery.superdelivery.location.LocationHelper;
import com.skwen.delivery.superdelivery.location.Utils;
import com.skwen.delivery.superdelivery.login.bean.User;
import com.skwen.delivery.superdelivery.myGreenDao.manager.UserDBManager;
import com.skwen.delivery.superdelivery.order.WriteOrderActivity;
import com.skwen.delivery.superdelivery.query.QueryDelivery;
import com.skwen.delivery.superdelivery.receive.ReceiveDelivery;
import com.tencent.lbssearch.TencentSearch;
import com.tencent.lbssearch.httpresponse.BaseObject;
import com.tencent.lbssearch.httpresponse.HttpResponseListener;
import com.tencent.lbssearch.object.Location;
import com.tencent.lbssearch.object.param.Geo2AddressParam;
import com.tencent.lbssearch.object.param.SearchParam;
import com.tencent.lbssearch.object.result.Geo2AddressResultObject;
import com.tencent.lbssearch.object.result.SearchResultObject;
import com.tencent.map.geolocation.TencentGeofence;
import com.tencent.map.geolocation.TencentLocation;
import com.tencent.map.geolocation.TencentLocationManager;
import com.tencent.mapsdk.raster.model.BitmapDescriptor;
import com.tencent.mapsdk.raster.model.LatLng;
import com.tencent.mapsdk.raster.model.Marker;
import com.tencent.mapsdk.raster.model.MarkerOptions;
import com.tencent.tencentmap.mapsdk.map.MapView;
import com.tencent.tencentmap.mapsdk.map.TencentMap;
import com.tencent.tencentmap.mapsdk.map.UiSettings;
import com.yzq.zxinglibrary.Consants;
import com.yzq.zxinglibrary.android.CaptureActivity;

import java.util.ArrayList;
import java.util.List;

import io.reactivex.Observable;
import io.reactivex.functions.Consumer;

/**
 *  1 主界面自动定位并发送位置到服务端
 *  2 从服务端获取快递员以及快递员定位信息
 *  3 地图上标注快递员位置以及距离
 *  4 用户发出订单
 *  5 系统派单，快递员接单
 *  6 地图上标注快递员距离以及给用户显示快递员行走路线
 */

public class MainActivity extends BaseActivity implements NavigationView.OnNavigationItemSelectedListener, View.OnTouchListener {


    private ActivityMainBinding mainBinding;
    private MapView mapView;
    private TencentLocationManager locationManager;
    private Marker mLocationMarker;
    private TencentMap mTencentMap;

    private LocationHelper mLocationHelper;
    private Handler handler = new Handler();
    private List<Marker> markerList = new ArrayList<>();

    private ImageView user_icon;
    private TextView user_name, user_balance, user_phone;

    private int REQUEST_CODE_SCAN = 1101;
    private User mUser;

    /**
     * 使用一个标志, 防止 requestLocationUpdates 和 removeUpdates 被多次重复调用.
     * (注,多次调用不会产生任何问题)
     */
    private boolean mStarted;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mainBinding = DataBindingUtil.setContentView(this, R.layout.activity_main);
        initView();
        mapView = mainBinding.appBarMain.contentMain.mapView;
        mapView.onCreate(savedInstanceState);
        mLocationHelper = new LocationHelper(this);
        mainBinding.appBarMain.toolbar.setTitle("");
        setSupportActionBar(mainBinding.appBarMain.toolbar);
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, mainBinding.drawerLayout, mainBinding.appBarMain.toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        mainBinding.drawerLayout.addDrawerListener(toggle);
        toggle.syncState();
        mainBinding.navView.setNavigationItemSelectedListener(this);
        mTencentMap = mapView.getMap();
        mTencentMap.setTrafficEnabled(true);
        mTencentMap.setZoom(18);
        mTencentMap.setInfoWindowAdapter(new TencentMap.InfoWindowAdapter() {

            //infoWindow关闭后调用，用户回收View
            @Override
            public void onInfoWindowDettached(Marker arg0, View arg1) {
                // TODO Auto-generated method stub

            }
            //infoWindow弹出前调用，返回的view将作为弹出的infoWindow
            @Override
            public View getInfoWindow(Marker arg0) {
                // TODO Auto-generated method stub
                return null;
            }
        });
        setMapUI();
        doMyLoc();
        mainBinding.appBarMain.contentMain.btnMyLocation.setOnClickListener(v -> {
            doMyLoc();
        });

    }

    private void initView() {
        UserDBManager userDbManager = UserDBManager.getInstance(this);
        List<User> list = userDbManager.queryUserList();
        if (list != null && list.size() > 0) {
            mUser = list.get(0);
        }
//        mUser = (User) getIntent().getSerializableExtra("user");
        user_icon = (ImageView) mainBinding.navView.getHeaderView(0).findViewById(R.id.user_icon);

        user_name = (TextView) mainBinding.navView.getHeaderView(0).findViewById(R.id.user_name);

        user_balance = (TextView) mainBinding.navView.getHeaderView(0).findViewById(R.id.user_balance);

        user_phone = (TextView) mainBinding.navView.getHeaderView(0).findViewById(R.id.user_phone);

        if (mUser != null) {

            if (!TextUtils.isEmpty(mUser.getUserName())) {
                user_name.setText(mUser.getUserName());
            }
            if (!TextUtils.isEmpty(mUser.getUserPhone())) {
                user_phone.setText(mUser.getUserPhone());
            }

            user_icon.setOnClickListener(v -> {
                Snackbar.make(v, "换头像", Snackbar.LENGTH_LONG)
                        .setAction("Action", null).show();
            });

            user_name.setOnClickListener(v -> {
                Snackbar.make(v, "个人信息设置", Snackbar.LENGTH_LONG)
                        .setAction("Action", null).show();
            });

            user_phone.setOnClickListener(v -> {
                Snackbar.make(v, "修改绑定手机", Snackbar.LENGTH_LONG)
                        .setAction("Action", null).show();
            });
        }

        mainBinding.appBarMain.contentMain.myLocationTips.setOnClickListener(v -> {
            if (!TextUtils.isEmpty(mainBinding.appBarMain.contentMain.myLocationAddress.getText())) {
                String address = mainBinding.appBarMain.contentMain.myLocationAddress.getText().toString();
                Intent intent = new Intent(MainActivity.this, WriteOrderActivity.class);
                intent.putExtra("address", address);
                startActivity(intent);
            } else {
                Snackbar.make(v, "地址为空", Snackbar.LENGTH_SHORT)
                        .setAction("Action", null).show();
            }
        });
        mainBinding.appBarMain.contentMain.myLocationAddressRequest.setOnClickListener(v -> {
            if (!TextUtils.isEmpty(mainBinding.appBarMain.contentMain.myLocationAddress.getText())) {
                String address = mainBinding.appBarMain.contentMain.myLocationAddress.getText().toString();
                Intent intent = new Intent(MainActivity.this, WriteOrderActivity.class);
                intent.putExtra("address", address);
                startActivity(intent);
            } else {
                Snackbar.make(v, "地址为空", Snackbar.LENGTH_SHORT)
                        .setAction("Action", null).show();
            }
        });
        mainBinding.appBarMain.toolbarTitle.setOnClickListener(v -> {
            Intent intent = new Intent(MainActivity.this, CityActivity.class);
            intent.putExtra("name", mainBinding.appBarMain.toolbarTitle.getText().toString());
            startActivityForResult(intent, 2001);
        });
    }

    // 生成 poi item
    private Marker createPoiItem(TencentGeofence geofence) {
        Marker marker = mTencentMap.addMarker(new MarkerOptions().
                position(new LatLng(geofence.getLatitude(), geofence.getLongitude())).
                title(geofence.getTag()).
                snippet(Utils.fmt(geofence.getLatitude()) + ","
                        + Utils.fmt(geofence.getLongitude()) + ","
                        + geofence.getRadius()));
        return marker;
    }


    private void doMyLoc() {
//        if (mLocationHelper.getLastLocation() != null) {
//            animateTo(mLocationHelper.getLastLocation()); // 已有最新位置
//        } else {
        showLoading();
////            mLocationHelper.start(new Runnable() {
////                public void run() {
////                    TencentLocation location = mLocationHelper.getLastLocation();
////                    animateTo(location);
////                }
////            });
//            mLocationHelper.start(() -> {
//                TencentLocation location = mLocationHelper.getLastLocation();
//                animateTo(location);
//            });
//        }
        handler.postDelayed(() -> {
            animateTo(App.getLocation());
        }, 1000);

    }

    private void animateTo(TencentLocation location) {
        stopLoading();
        if (location == null) {
            return;
        }
        mTencentMap.animateTo(new LatLng(location.getLatitude(), location.getLongitude()));
        mTencentMap.setCenter(new LatLng(location.getLatitude(), location.getLongitude()));

        if (!TextUtils.isEmpty(location.getCity()))
            mainBinding.appBarMain.toolbarTitle.setText(location.getCity());
        handler.postDelayed(this::updatePosition
                , 1000);
    }

    private void updatePosition() {
        showLoading();
        double lat = mTencentMap.getMapCenter().getLatitude();
        double lng = mTencentMap.getMapCenter().getLongitude();
        TencentSearch tencentSearch = new TencentSearch(this);
        Geo2AddressParam param = new Geo2AddressParam().location(new Location((float) lat, (float) lng));
        tencentSearch.geo2address(param, new HttpResponseListener() {
            @Override
            public void onSuccess(int i, BaseObject baseObject) {
                Geo2AddressResultObject oj = (Geo2AddressResultObject) baseObject;
                String msg = oj.result.formatted_addresses.recommend;
                Geo2AddressResultObject.ReverseAddressResult.AdInfo adInfo = oj.result.ad_info;
                mainBinding.appBarMain.toolbarTitle.setText(adInfo.city);
                mainBinding.appBarMain.contentMain.myLocationAddress.setText(msg);
                stopLoading();
            }

            @Override
            public void onFailure(int i, String s, Throwable throwable) {
                stopLoading();
            }
        });


        Location location = new Location().lat((float) lat).lng((float) lng);
        SearchParam.Nearby nearBy = new SearchParam.Nearby().point(location);
        nearBy.r(3000);
        SearchParam object = new SearchParam().keyword("银行").boundary(nearBy);

        tencentSearch.search(object, new HttpResponseListener() {
            @Override
            public void onSuccess(int i, BaseObject baseObject) {
                SearchResultObject resultObject = (SearchResultObject) baseObject;

                for (Marker marker : markerList) {
                    if (marker != null) {
                        marker.remove();
                    }
                }
                markerList.clear();
                Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.mipmap.main_tips_point);
                BitmapDescriptor bitmapDescriptor = new BitmapDescriptor(bitmap);
                if (resultObject.data != null){
                    Observable.fromIterable(resultObject.data)
                            .subscribe(new Consumer<SearchResultObject.SearchResultData>() {
                                @Override
                                public void accept(SearchResultObject.SearchResultData searchResultData) throws Exception {
                                    Marker marker = mTencentMap.addMarker(new MarkerOptions()
                                            .position(new LatLng(searchResultData.location.lat, searchResultData.location.lng))
//                                            .title(searchResultData.title)
                                            .icon(bitmapDescriptor)//
                                            .draggable(true));
//                                    marker.showInfoWindow();// 设置默认显示一个infoWindow
                                    markerList.add(marker);
                                }
                            });
                }


//                for (int j = 0; resultObject.data != null && j < resultObject.data.size(); j++) {
//
//                    SearchResultObject.SearchResultData data = resultObject.data.get(j);
//                    Marker marker = mTencentMap.addMarker(new MarkerOptions()
//                            .position(new LatLng(data.location.lat, data.location.lng))
//                            .title(data.title)
//                            .icon(bitmapDescriptor)//
//                            .draggable(true));
//                    marker.showInfoWindow();// 设置默认显示一个infoWindow
//                    markerList.add(marker);
//                }
//                BitmapDescriptorFactory
//                        .defaultMarker()

            }

            @Override
            public void onFailure(int i, String s, Throwable throwable) {

            }
        });

    }


    /**
     * REQ_LEVEL_GEO	0	包含经纬度
     * REQ_LEVEL_NAME	1	包含经纬度, 位置名称, 位置地址
     * REQ_LEVEL_ADMIN_AREA	3	包含经纬度，位置所处的中国大陆行政区划
     * REQ_LEVEL_POI	4	包含经纬度，位置所处的中国大陆行政区划及周边POI列表
     */


    private void getLocation() {

        if (Build.VERSION.SDK_INT >= 23) {
            String[] permissions = {
                    Manifest.permission.ACCESS_COARSE_LOCATION,
                    Manifest.permission.READ_PHONE_STATE,
                    Manifest.permission.WRITE_EXTERNAL_STORAGE
            };

            if (checkSelfPermission(permissions[0]) != PackageManager.PERMISSION_GRANTED) {
                requestPermissions(permissions, 0);
            }
        } else {
//            TencentLocationRequest request = TencentLocationRequest.create();
//            request.setInterval(3000);
//            request.setRequestLevel(REQUEST_LEVEL_NAME);
//            request.setAllowCache(true);
//            locationManager = TencentLocationManager.getInstance(this);
//            int error = locationManager.requestLocationUpdates(request, this);
//            startLocation(null);
        }
    }

    private void setMapUI() {
        //设置logo到屏幕底部中心
        mapView.getUiSettings().setLogoPosition(UiSettings.LOGO_POSITION_RIGHT_BOTTOM);
//设置比例尺到屏幕右下角
        mapView.getUiSettings().setScaleViewPosition(UiSettings.SCALEVIEW_POSITION_LEFT_BOTTOM);
//启用缩放手势(更多的手势控制请参考开发手册)
        mapView.getUiSettings().setZoomGesturesEnabled(true);
        mapView.getUiSettings().setAnimationEnabled(true);
        mapView.getUiSettings().setScaleControlsEnabled(true);
        mapView.setOnTouchListener(this);
    }

    @Override
    public void onBackPressed() {
        //DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        if (mainBinding.drawerLayout.isDrawerOpen(GravityCompat.START)) {
            mainBinding.drawerLayout.closeDrawer(GravityCompat.START);
        } else {
            super.onBackPressed();
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onPrepareOptionsMenu(Menu menu) {


        return super.onPrepareOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        if (id == R.id.action_message) {
            Intent intent = new Intent(MainActivity.this,
                    CaptureActivity.class);
            startActivityForResult(intent, REQUEST_CODE_SCAN);
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @SuppressWarnings("StatementWithEmptyBody")
    @Override
    public boolean onNavigationItemSelected(MenuItem item) {
        // Handle navigation view item clicks here.
        int id = item.getItemId();
        switch (id) {
            case R.id.my_receive:
                startActivity(new Intent(MainActivity.this, ReceiveDelivery.class));
                break;
            case R.id.my_check:
                startActivity(new Intent(MainActivity.this, QueryDelivery.class));
                break;
            case R.id.my_money:
                showToast(mainBinding.getRoot(), "我的钱包页面");
                break;
            case R.id.my_receive_adress:
                startActivity(new Intent(MainActivity.this, ReceiveAddress.class));
                break;
            case R.id.my_send_adress:
                startActivity(new Intent(MainActivity.this, SendAddress.class));
                break;
            case R.id.my_receive_order:
                startActivity(new Intent(MainActivity.this, SendDeliveryOrder.class));
                break;
            case R.id.my_send_order:

                break;
            case R.id.my_service:

                break;
            case R.id.about_us:

                break;
            case R.id.setting:

                break;
        }

        //DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        mainBinding.drawerLayout.closeDrawer(GravityCompat.START);
        return true;
    }

//
//    protected void setTitleName(String name) {
//        mainBinding.appBarMain.toolbarTitle.setText(name);
//    }


    @Override
    protected void onDestroy() {
        mapView.onDestroy();
        super.onDestroy();
//        stopLocation(null);
    }

    @Override
    protected void onPause() {
        mapView.onPause();
        super.onPause();
    }

    @Override
    protected void onResume() {
        mapView.onResume();
        super.onResume();
    }

    @Override
    protected void onStop() {
        mapView.onStop();
        super.onStop();
    }

//    @Override
//    public void onLocationChanged(TencentLocation location, int error, String reason) {
//        if (TencentLocation.ERROR_OK == error) {
//            // 定位成功
//            if (!TextUtils.isEmpty(location.getName())) {
//               mainBinding.appBarMain.toolbarTitle.setText(location.getName());
//            }
//
//            if (!TextUtils.isEmpty(location.getAddress())) {
//                Log.i("skwen", location.getAddress());
//            }
//
//            LatLng latLngLocation = new LatLng(location.getLatitude(), location.getLongitude());
//            // 更新 location Marker
//            if (mLocationMarker == null) {
//                mLocationMarker =
//                        mTencentMap.addMarker(new MarkerOptions().
//                                position(latLngLocation).
//                                icon(BitmapDescriptorFactory.fromResource(R.mipmap.location_icon)));
//            } else {
//                mLocationMarker.setPosition(latLngLocation);
//            }
//            mTencentMap.setCenter(latLngLocation);
//            if (mAccuracyCircle == null) {
//                mAccuracyCircle = mTencentMap.addCircle(new CircleOptions().
//                        center(latLngLocation).
//                        radius(location.getAccuracy()).
//                        fillColor(0x884433ff).
//                        strokeColor(0xaa1122ee).
//                        strokeWidth(1));
//            } else {
//                mAccuracyCircle.setCenter(latLngLocation);
//                mAccuracyCircle.setRadius(location.getAccuracy());
//            }
//
//
//        } else {
//            // 定位失败
//        }
//
//    }
//
//    @Override
//    public void onStatusUpdate(String name, int status, String desc) {
//        Log.i("skwen", "name:" + name + "  status:" + status + " desc:" + desc);
//    }


    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
//        startLocation(null);
    }

//
//    // 响应点击"停止"
//    public void stopLocation(View view) {
//        if (mStarted) {
//            mStarted = false;
//            locationManager.removeUpdates(this);
//
//            updateLocationStatus("停止定位");
//        }
//    }
//
//    // 响应点击"开始"
//    public void startLocation(View view) {
//        if (!mStarted) {
//            mStarted = true;
//            // 创建定位请求
//            TencentLocationRequest request = TencentLocationRequest
//                    .create()
//                    .setRequestLevel(
//                            TencentLocationRequest.REQUEST_LEVEL_ADMIN_AREA)
//                    .setInterval(5000); // 设置定位周期, 建议值为 1s-20s
//            locationManager = TencentLocationManager.getInstance(this);
//            // 开始定位
//            locationManager.requestLocationUpdates(request, this, getMainLooper());
//
//            updateLocationStatus("开始定位: " + request + ", 坐标系="
//                    + DemoUtils.toString(locationManager.getCoordinateType()));
//        }
//    }


    // ====== location callback

    private void updateLocationStatus(String message) {


    }


    static void toast(Context context, CharSequence text) {
        Toast.makeText(context, text, Toast.LENGTH_SHORT).show();
    }

    @Override
    public boolean onTouch(View v, MotionEvent event) {
        if (event.getAction() == MotionEvent.ACTION_UP) {
            updatePosition();
        }
        return false;
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        // 扫描二维码/条码回传
        if (requestCode == REQUEST_CODE_SCAN && resultCode == RESULT_OK) {
            if (data != null) {
                String content = data.getStringExtra(Consants.CODED_CONTENT);
                toast(this, content);
            }
        } else if (requestCode == 2001 && resultCode == 2002) {
            City city = (City) data.getSerializableExtra("city");
            if (city != null) {
                if (!TextUtils.isEmpty(city.getName())) {
                    stopLoading();
                    mainBinding.appBarMain.toolbarTitle.setText(city.getName());
                    TencentSearch tencentSearch = new TencentSearch(this);
                    SearchParam.Region r = new SearchParam.Region().poi(city.getName());
                    SearchParam param = new SearchParam().keyword("银行").boundary(r);
                    param.page_size(10);
                    tencentSearch.search(param, new HttpResponseListener() {
                        @Override
                        public void onSuccess(int i, BaseObject baseObject) {
                            SearchResultObject oj = (SearchResultObject) baseObject;
                            if (oj.data != null && oj.data.size() > 0) {
                                stopLoading();
                                SearchResultObject.SearchResultData data = oj.data.get(0);
                                if (!TextUtils.isEmpty(data.address))
                                    mainBinding.appBarMain.contentMain.myLocationAddress.setText(data.address);
                                if (data.location != null) {
                                    mTencentMap.animateTo(new LatLng(data.location.lat, data.location.lng));
                                    mTencentMap.setCenter(new LatLng(data.location.lat, data.location.lng));
                                    handler.postDelayed(() -> updatePosition(), 1000);
                                }
                            }
                        }

                        @Override
                        public void onFailure(int i, String s, Throwable throwable) {
                            stopLoading();
                        }
                    });

                }
            }
        }
    }
}
